package com.wisewin.pose.config;

import com.wisewin.pose.util.env.Env;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;

@Configuration
public class WSOkHttpConfiguration {

    private Integer connectTimeout = Integer.parseInt(Env.getProperty("okHttpConnectionTimeout"));
    private Integer readTimeout = Integer.parseInt(Env.getProperty("okHttpReadTimeout"));
    private Integer writeTimeout = Integer.parseInt(Env.getProperty("okHttpWriteTimeout"));
    private Integer maxIdleConnections = Integer.parseInt(Env.getProperty("okHttpMaxIdleConnections"));
    private Long keepAliveDuration = Long.parseLong(Env.getProperty("okHttpKeepAliveDuration"));

    @Bean
    public OkHttpClient okHttpClient() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return  new OkHttpClient.Builder()
                // 是否开启缓存
                .retryOnConnectionFailure(false)
                .connectionPool(new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.MILLISECONDS))
                .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
                .readTimeout(readTimeout, TimeUnit.MILLISECONDS)
                .writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)
                .hostnameVerifier((hostname, session) -> true)
                .addInterceptor(loggingInterceptor)
                .addInterceptor(chain -> {
                    Request original = chain.request();
                    // 对于SOAP 1.1， 如果是soap1.2 应是Content-Type: application/soap+xml; charset=utf-8
                    Request.Builder requestBuilder = original.newBuilder()
                            .header("Content-Type", "text/xml;charset=UTF-8")
                            .header("Accept-Language", "zh-CN,zh;")
                            .method(original.method(), original.body());
                    Request request = requestBuilder.build();
                    return chain.proceed(request);
                })
                .build();
    }
}
